package com.samnative.pineapple.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.shashank.sony.fancytoastlib.FancyToast;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.MD5Util;
import com.samnative.pineapple.utils.TimeCount;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.WenxinDialog;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import ezy.ui.view.RoundButton;


/**
 * 注册
 * Created by Wy on 2018/6/25.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener,
        TimeCount.ITimeCountListener {

    public static RegisterActivity instance = null;
    /**
     * 登录密码
     */
    private EditText et_pwd;
    /**
     * 手机号码
     */
    private EditText et_phone;
    /**
     * 验证码
     */
    private EditText et_verity_code;
    /**
     * 推荐人手机好
     */
    private EditText et_referrer;
    /**
     * 获取验证码
     */
    private RoundButton tv_get_verity;
    /**
     * 用户协议
     */
    private TextView protocol_tv;

    /**
     * 定时间器
     */
    private TimeCount mTimeCount;

    /**
     * 注册按钮
     */
    private TextView btn_login;

    /**
     * 协议勾选按钮
     */
    private CheckBox protocol_ck;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = RegisterActivity.this;
        mTimeCount = new TimeCount(60000, 1000);
        mTimeCount.setTimerCountListener(this);
        find(R.id.tv_login).setOnClickListener(this);
        find(R.id.close_iv).setOnClickListener(this);
        et_referrer = find(R.id.et_referrer);
        btn_login = find(R.id.btn_login);
        btn_login.setOnClickListener(this);
        et_pwd = find(R.id.et_pwd);
        et_phone = find(R.id.et_phone);
        et_verity_code = find(R.id.et_verity_code);
        tv_get_verity = find(R.id.tv_get_verity);
        protocol_tv = find(R.id.protocol_tv);
        protocol_ck = find(R.id.protocol_ck);
        setXieyiStyle(protocol_tv);
//        protocol_tv.setOnClickListener(this);
        tv_get_verity.setOnClickListener(this);


        //设置显示或隐藏密码
        ((CheckBox) findViewById(R.id.ib_change_pw)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                et_pwd.setSelection(et_pwd.getText().length());
            }
        });


        if (!AppPrefer.getInstance(mContext).getBoolean(AppPrefer.isPrivacyPolicy, false)) {
            //弹出隐私协议，提示
            WenxinDialog.getInstance(mContext, new WenxinDialog.Click() {
                @Override
                public void ok() {
                    AppPrefer.getInstance(mContext).put(AppPrefer.isPrivacyPolicy, true);
                }

                @Override
                public void cancel() {
                    finish();
                }
            }).show();
        }


    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.close_iv:
                finish();
                break;
            case R.id.btn_login:

                if (et_phone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                    return;
                }

                if (et_verity_code.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.verify_input_tips), FancyToast.WARNING, false);
                    return;
                }


                if (et_pwd.getText().toString().isEmpty() || et_pwd.getText().toString().length() < 6) {
                    FancyToast.showToast(mContext, getString(R.string.input_pwd), FancyToast.WARNING, false);
                    return;
                }



                if (!protocol_ck.isChecked()) {
                    FancyToast.showToast(mContext, "请阅读并同意《注册协议》及《隐私政策》", FancyToast.WARNING, false);
                    return;
                }

                register();
                break;
            case R.id.tv_get_verity:
                if (et_phone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                } else {
                    requestCode();
                }

                break;
            case R.id.tv_login:
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                finish();
                break;
//            case R.id.protocol_tv:
//                Intent intent1 = new Intent(mContext, Webview2Activity.class);
//                intent1.putExtra("url", Config.WEB_URL + "/Introduction/Index/registDeal");
//                startActivity(intent1);
//                break;
        }
    }



    /**
     * 获取验证码
     */
    private void requestCode() {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", et_phone.getText().toString().trim());
        map.put("devicenumber", Config._uuid);
        map.put("sendType", "register_");
        map.put("privatekey", MD5Util.getMD5Str(et_phone.getText().toString().trim() + Config._API_KEY));
        map.put("_apiname", "user.public.sendvalicode");

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                mTimeCount.start();
                tv_get_verity.setEnabled(false);
                tv_get_verity.setOnClickListener(null);

                FancyToast.showToast(mContext, getString(R.string.verify_send_success), FancyToast.INFO, false);
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });
    }



//    /**
//     * 控制注册按钮状态
//     */
//    private void setBtnStatus(EditText... editTexts) {
//        for (int i = 0; i < editTexts.length; i++) {
//            editTexts[i].addTextChangedListener(new TextWatcher() {
//                @Override
//                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//                }
//
//                @Override
//                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//                }
//
//                @Override
//                public void afterTextChanged(Editable editable) {
//                    if (et_pwd.getText().toString().trim().length() < 6
//                            || et_pay_pwd.getText().toString().trim().length() < 6
//                            || et_inviter.getText().toString().trim().isEmpty()
//                            || et_phone.getText().toString().trim().length() < 5
//                            || et_verity_code.getText().toString().trim().length() < 6) {
//                        btn_login.setBackground(getResources().getDrawable(
//                                R.drawable.login_btn_selector3));
//                        btn_login.setTextColor(getResources().getColor(R.color.main_gray_bg));
//                        btn_login.setClickable(false);
//                    } else {
//                        btn_login.setBackground(getResources().getDrawable(
//                                R.drawable.login_btn_selector));
//                        btn_login.setTextColor(getResources().getColor(R.color.main_white));
//                        btn_login.setClickable(true);
//                    }
//
//                }
//            });
//        }
//    }

    /**
     * 注册
     */
    private void register() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", et_phone.getText().toString().trim());
//        map.put("typeid", nice_spinner.getTag().toString());
        map.put("valicode", MD5Util.getMD5Str(et_verity_code.getText().toString().trim() + Config._API_KEY));
        map.put("loginpwd", MD5Util.getMD5Str(et_pwd.getText().toString().trim()));
        map.put("confirmpwd", MD5Util.getMD5Str(et_pwd.getText().toString().trim()));
        if (!TextUtils.isEmpty(et_referrer.getText().toString())) {
            map.put("parentname", et_referrer.getText().toString().trim());//推荐人
        }
        map.put("devtype", "A");
        map.put("_apiname", "user.register.register");

        HttpRequest.post(this, null, map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                FancyToast.showToast(mContext, getString(R.string.success_reg), FancyToast.SUCCESS, false);
                try {
//                    RegisterModel registerModel = GsonUtils.fromJson(result.toString(), RegisterModel.class);
//                    AppPrefer.getInstance(mContext).put(AppPrefer.mtoken, registerModel.getData().getMtoken());

                    startActivity(new Intent().setClass(mContext, LoginActivity.class));
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });


    }

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
//        tv_get_verity.setBackgroundDrawable((getResources()
//                .getDrawable(R.drawable.btn_verify_selector_gray)));
        tv_get_verity.setText((millisUntilFinished / 1000) + getString(R.string.verify_confirm));
        tv_get_verity.setEnabled(false);
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
//        tv_get_verity.setBackgroundDrawable((getResources()
//                .getDrawable(R.drawable.btn_verify_selector_red)));
        tv_get_verity.setText(getString(R.string.verify_send_again));
        tv_get_verity.setEnabled(true);
        tv_get_verity.setOnClickListener(this);
    }



    /**
     * 设置协议样式
     */
    public void setXieyiStyle(TextView textview) {

        String str = textview.getText().toString();

        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(str);

        final int start = str.indexOf("《");//第一个出现的位置
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
//                Toast.makeText(mContext, "《用户协议》",
//                        Toast.LENGTH_SHORT).show();
                Intent intent1 = new Intent(mContext, Webview2Activity.class);
                intent1.putExtra("url", Config.WEB_URL + "/Introduction/Index/registDeal");
                startActivity(intent1);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.main_color));       //设置文件颜色
                // 去掉下划线
                ds.setUnderlineText(false);
            }

        }, start, start + 6, 0);

        final int end = str.lastIndexOf("《");//最后一个出现的位置
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
//                Toast.makeText(mContext, "《隐私政策》",
//                        Toast.LENGTH_SHORT).show();
                Intent intent1 = new Intent(mContext, Webview2Activity.class);
                intent1.putExtra("url", Config.WEB_URL + "/Introduction/index/privacy");
                startActivity(intent1);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.main_color));       //设置文件颜色
                // 去掉下划线
                ds.setUnderlineText(false);
            }

        }, end, end + 6, 0);

        textview.setMovementMethod(LinkMovementMethod.getInstance());
        textview.setText(ssb, TextView.BufferType.SPANNABLE);
    }

}
